package com.rockxin.cat.utils.imageUtils;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;


import com.rockxin.cat.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static android.R.attr.path;

/**
 * <b>类名称：   </b> ImageUtils <br/>
 * <b>类描述：   </b><br/>
 * <b>创建人：   </b> leishun <br/>
 * <b>创建时间： </b> 2017/4/12 下午2:05 <br/>
 * <b>修改人：   </b><br/>
 * <b>修改时间： </b><br/>
 * <b>修改备注： </b><br/>
 *
 * @version 1.0.0 <br/>
 */
public class ImageUtils {
    private static final String TAG = ImageUtils.class.getSimpleName();
    public static String saveDir = Environment.getExternalStorageDirectory().getPath() + "/temp_image/";

    public static final int CAMERA_RESULT = 100;
    public static final int RESULT_LOAD_IMAGE = 200;
    public static File mPhotoFile;

    /**
     * 打開系統相冊
     *
     * @param activity
     */
    public static void openPhotoComponent(final FragmentActivity activity) {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        activity.startActivityForResult(intent, RESULT_LOAD_IMAGE);

    }

    /**
     * 选取图片
     *
     * @param activity //拍照和系统相册
     */
    public static void justGetImage(final FragmentActivity activity) {
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog();
        FragmentManager fm = activity.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.add(actionSheetDialog, "photo");
        fragmentTransaction.commitAllowingStateLoss();
        // actionSheetDialog.show(activity.getSupportFragmentManager(), "photo");
        actionSheetDialog.bindActivity(activity);
        actionSheetDialog.setActionSheetListener(new ActionSheetDialog.ActionSheetListener() {
            @Override
            public void onTakePhoto() {
                //拍照
                openCameraComponent(activity);
            }

            @Override
            public void onChooseFrom() {
                //从手机相册选择
                openPhotoComponent(activity);//單圖
            }
        });
    }


    /**
     * 打开相机
     *
     * @param activity
     */
    public static void openCameraComponent(final FragmentActivity activity) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String st = "SD卡不存在，不能拍照";
            Toast.makeText(activity, st, Toast.LENGTH_SHORT);
            return;
        }
        File savePath = new File(saveDir);
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".jpg";//使用毫秒值作为文件名
        mPhotoFile = new File(saveDir, fileName);
        mPhotoFile.delete();
        if (!mPhotoFile.exists()) {
            try {
                mPhotoFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(activity, "文件路径不存在", Toast.LENGTH_SHORT);
                return;
            }
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //7.0以前
      /*  intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(mPhotoFile));
        activity.startActivityForResult(intent, CAMERA_RESULT);*/
        if (Build.VERSION.SDK_INT < 24) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));  // set the image file name
        } else {
            /*ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, mPhotoFile.getAbsolutePath());
            Uri uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);*/
            Uri uriForFile = FileProvider.getUriForFile(activity, activity.getPackageName() + "provider", mPhotoFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uriForFile);
        }
        try {
            activity.startActivityForResult(intent, CAMERA_RESULT);
        } catch (Exception e) {
            e.printStackTrace();
            //ToastUtils.showShortToastSafe("还没有权限，请去设置开启权限");
            AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.myAlertDialog);
            builder.setMessage("您没有开启相机权限,可能导致该功能无法使用,是否去开启权限？");
            builder.setPositiveButton(activity.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton(activity.getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Uri packageURI = Uri.parse("package:" + activity.getPackageName());
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                    activity.startActivity(intent);
                    dialog.dismiss();
                }
            });
            builder.show();
        }

    }

    /**
     * 打开相机
     *
     * @param activity
     * @param requestCode 返回码
     */
    public static void openCameraComponent(FragmentActivity activity, int requestCode) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // String st = "SD卡不存在，不能拍照";
            // Toast.makeText(activity, st, Toast.LENGTH_SHORT);
            return;
        }
        File savePath = new File(saveDir);
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".jpg";//使用毫秒值作为文件名
        mPhotoFile = new File(saveDir, fileName);
        mPhotoFile.delete();
        if (!mPhotoFile.exists()) {
            try {
                mPhotoFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                //Toast.makeText(activity, "文件路径不存在", Toast.LENGTH_SHORT);
                return;
            }
        }
        Intent intent = new Intent(
                "android.media.action.IMAGE_CAPTURE");
        //7.0以前
      /*  intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(mPhotoFile));
        activity.startActivityForResult(intent, CAMERA_RESULT);*/
        ContentValues contentValues = new ContentValues(1);
        contentValues.put(MediaStore.Images.Media.DATA, mPhotoFile.getAbsolutePath());
        Uri uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        activity.startActivityForResult(intent, CAMERA_RESULT);
    }


    /**
     * sdcard是否存在
     *
     * @return
     */
    public static boolean isSDCardExist() {
        String status = Environment.getExternalStorageState();
        // 如果存在则获取SDCard目录
        return status.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取文件的路径
     *
     * @param data
     * @return
     */
    public static String getPicPathFromData(Intent data, FragmentActivity mBaseActivity) {
        Uri uri = getUri(data, mBaseActivity);
        if (uri == null) {
            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
            uri = Uri.parse(MediaStore.Images.Media.insertImage(mBaseActivity.getContentResolver(), bitmap, null, null));

        }
        ContentResolver resolver = mBaseActivity.getContentResolver();
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            //	cursor = resolver.query(originalUri, proj, null, null, null);
            cursor = resolver.query(uri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            Log.e(TAG, "FOR_SELECT_PHOTO Exception:" + e.toString());
            return null;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    /**
     * 解决小米手机上获取图片路径为null的情况
     *
     * @param intent
     * @return
     */
    public static Uri getUri(Intent intent, FragmentActivity mBaseActivity) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = mBaseActivity.getContentResolver();
                String buff = "(" +
                        MediaStore.Images.ImageColumns.DATA +
                        "=" + "'" + path + "'" +
                        ")";
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff, null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index != 0) {
                    Uri uri_temp = Uri.parse("content://media/external/images/media/" + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
                cur.close();
            }
        }
        return uri;
    }

    // 压缩处理图片
    @SuppressLint("SdCardPath")
    public static void getThumbImage(String filePath, IGetImageListener imageListener, int size) {
        if (filePath == null) {
            Log.e("filePath---->>>>", "添加图片失败,请重试");
            return;
        }
        // 生成图
        save(filePath, size, "big");
        Log.e("filePath---->>>>", filePath);

        File bigFile = new File(getImageFilePath(filePath, "big"));
        if (bigFile.exists()) {
            imageListener.loadSuccess(new String[]{bigFile.getAbsolutePath(), ""});
//            String fileSize = getAutoFileOrFilesListSize(bigFile.getAbsolutePath());
//            Log.e(TAG, fileSize);
        } else {
            imageListener.loadSuccess(new String[]{});
        }
    }


    /**
     * 保存
     *
     * @param filePath
     * @param size
     * @param tempName
     */
    private static void save(String filePath, int size, String tempName) {
        try {
            Bitmap bm = getSmallBitmap(filePath);
            int degree = readPictureDegree(filePath);
            if (degree != 0) {// 旋转照片角度
                bm = rotateBitmap(bm, degree);
            }
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            FileOutputStream fos = new FileOutputStream(getImageFilePath(filePath, tempName));
            int options = 100;
            // 如果大于100kb则再次压缩,最多压缩三次
            while (bos.toByteArray().length / 1024 > size && options > 10) {
                // 清空bos
                bos.reset();
                // 这里压缩options%，把压缩后的数据存放到bos中
                bm.compress(Bitmap.CompressFormat.JPEG, options, bos);
                options -= 30;
            }
            Log.e(TAG, bos.toByteArray().length / 1024 + "kb");
            fos.write(bos.toByteArray());
            fos.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据路径获得图片并压缩返回bitmap
     *
     * @param filePath
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = calculateInSampleSize(options, 480, 800, filePath);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 获取图片的角度
     *
     * @param path
     * @return
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight, String filePath) {
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 1;
        if (height == -1 || width == -1) {
            try {
                ExifInterface exifInterface = new ExifInterface(filePath);
                int h = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, ExifInterface.ORIENTATION_NORMAL);//获取图片的高度
                int w = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, ExifInterface.ORIENTATION_NORMAL);//获取图片的宽度
                Log.i(TAG, "exif height: " + h);
                Log.i(TAG, "exif width: " + w);
                height = h;
                width = w;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = (heightRatio < widthRatio ? heightRatio : widthRatio);
        }
        return inSampleSize;
    }

    /**
     * 旋转图片
     *
     * @param bitmap
     * @param degree
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degree) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degree);
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
        }
        return bitmap;
    }

    /**
     * 得到图片名称的方法
     *
     * @return
     */
    public static String getImageFilePath(String filePath, String tmpFileNamePrefix) {
        String tempName = filePath.substring(filePath.lastIndexOf("/") + 1);
        Log.e("tempName---->>>>", tempName);
        File file = new File(saveDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return saveDir + tmpFileNamePrefix + "_" + tempName;
    }


    //保存图片到本地并更新图库
    public static String saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment
                .getExternalStorageDirectory().getPath() + File.separator + "ikaycity" + File.separator + "image");
        if (!appDir.exists()) {
            appDir.mkdirs();
            Log.e(TAG, "创建文件夹");
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        Log.e(TAG, "创建文件");
        File file = new File(appDir, fileName);
        Log.e(TAG, appDir + fileName);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
        return file.getAbsolutePath();
    }

    public static boolean isLongImg(File file, Bitmap bitmap) {
        if (file == null || file.length() == 0) {
            return false;
        }
        return bitmap.getHeight() > bitmap.getWidth() * 3 || file.length() >= 0.5 * 1024 * 1024;
    }

}
